package me.wangshier.leetcode.hard;

/**
 * 12. 最大UCC子串计算
 *
 * @Author: tongqianwen
 * @Date: 2025/3/5
 */
public class MaxSubstringEdit {
    public static int solution(int m, String s) {
        int count = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length - 2; i++) {
            // 检查当前位置是否可以形成 "UCC" 子串
            if (i + 2 < s.length() && s.charAt(i) == 'U' && s.charAt(i + 1) == 'C' && s.charAt(i + 2) == 'C') {
                count++;
                chars[i] = ' ';
                chars[i + 1] = ' ';
                chars[i + 2] = ' ';
                i += 3; // 跳过 "UCC" 子串
            }
        }

        for (int i = 0; i < chars.length - 1; i++) {
            if (m > 0) {
                // 检查UC, CC 字串
                if (chars[i] == 'U' && chars[i + 1] == 'C') {
                    count++;
                    m--;
                    chars[i] = ' ';
                    chars[i + 1] = ' ';
                } else if (chars[i] == 'C' && chars[i + 1] == 'C') {
                    count++;
                    m--;
                    chars[i] = ' ';
                    chars[i + 1] = ' ';
                }
            }
        }

        for (int i = 0; i < chars.length; i++) {
            if (m > 1) {
                // 检查U,C 字串
                if (chars[i] == 'U') {
                    count++;
                    m -= 2;
                    chars[i] = ' ';
                } else if (chars[i] == 'C') {
                    count++;
                    m -= 2;
                    chars[i] = ' ';
                }
            }
        }
        if (m > 0) {
            count += m / 3;
        }

        return count;
    }

    public static void main(String[] args) {
        System.out.println(solution(12, "UUUUUUUUUUUUUUUU") == 6);
        System.out.println(solution(3, "CUUUCUCUUUUCU") == 3);
        System.out.println(solution(1, "CC") == 1);
        System.out.println(solution(0, "UCC") == 1);
        System.out.println(solution(3, "UCUUCCCCC") == 3);
        System.out.println(solution(6, "U") == 2);
        System.out.println(solution(2, "UCCUUU") == 2);
    }

}
